package com.ruoyi.material.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.material.domain.*;
import com.ruoyi.material.domain.constant.FileConstant;
import com.ruoyi.material.domain.vo.FileRecordVo;
import com.ruoyi.material.domain.vo.FileTotalInfoVo;
import com.ruoyi.material.service.*;
import com.ruoyi.material.util.RandomlyGeneratedUtil;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 文件记录Controller
 *
 * @author ruoyi
 * @date 2021-07-10
 */
@RestController
@RequestMapping("/file/flie")
public class BaseFlieRecordController extends BaseController
{
    private Logger logger = LoggerFactory.getLogger(BaseFlieRecordController.class);

    @Autowired
    private IBaseFlieRecordService baseFlieRecordService;
    @Autowired
    private IBaseMaterialService baseMaterialService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBaseTagFileService baseTagFileService;
    @Autowired
    private IBaseLabelService baseLabelService;
    @Autowired
    private IBaseFileLabelService baseFileLabelService;

    /**
     * 查询文件记录列表
     */
    @PreAuthorize("@ss.hasPermi('file:flie:list')")
    @GetMapping("/list")
    public TableDataInfo list(BaseFlieRecord baseFlieRecord)
    {
        startPage();
        List<BaseFlieRecord> list = baseFlieRecordService.selectBaseFlieRecordList(baseFlieRecord);
        return getDataTable(list);
    }

    /**
     * 查询文件记录列表_目录结构
     */
//    @PreAuthorize("@ss.hasPermi('material:flie:list')")
    @GetMapping("/list_pcode")
    public TableDataInfo listByPcode(BaseFlieRecord bfr,String pcode, @RequestParam(value ="label" ,required = false) String label,@RequestParam(value = "paramLabels[]" ,required  = false) String[] paramLabels,HttpServletRequest request)
    {
        startPage();
        List<Integer> labels  = new ArrayList<>();
        if(label.trim()==""||label.trim()==null||label.trim().equals("null")){
            labels=null;
        }else {
            String[] labelids = label.split(",");
            Map<Integer, Integer> labelMap = new HashMap<>();//<labelCode,typeCode>
            for (int i = 0; i < labelids.length; ) {
                labelMap.put(Integer.parseInt(labelids[i + 1].trim()), Integer.parseInt(labelids[i].trim()));
                i += 2;
            }
            for (Integer k : labelMap.keySet()) {
                labels.add(k);
            }
        }

//        List<FileRecordVo> list = baseFlieRecordService.selectBaseFlieRecordvOByPCodeAndBaseFileRecord(bfr,pcode);
        List<FileRecordVo> list =baseFlieRecordService.selectBaseFileRecordVoNewByLabel(bfr.getOriginalFileName(),bfr.getContentType(),pcode,labels);
        Collections.sort(list,new Comparator<FileRecordVo>(){
            @Override
            public int compare(FileRecordVo o1, FileRecordVo o2) {
                return isFile(o1.getContentType())-isFile(o2.getContentType());
            }
        });

        return getDataTable(list);
    }
//当前目录搜索，记录此目录下的文件夹的code, 再一个个作为p_code搜索（调用已有的listByPcode），直到此目录下没有文件夹，即文件夹codeList为空，停止


    /**
     * 汇总信息
     */
    @GetMapping("/total_info")
    public AjaxResult selectTotalInfo(BaseFlieRecord baseFlieRecord){
        FileTotalInfoVo total = baseFlieRecordService.selectTotalInfo();
        if (total.getTotalFileInfo() == 0){
            total = new FileTotalInfoVo();
            total.setFileSize(new Double(0));
            return AjaxResult.success(total);
        }
        // b kb mb gb t
        int count = 0;
        while (total.getFileSize() > 1024 && count  < 5 ){
            total.setFileSize(total.getFileSize() / 1024);
            count ++;
            logger.debug("count [{}]",count);
        }
        if (count == 0){
            total.setUnit("B");
        }
        if (count == 1){
            total.setUnit("KB");
        }else if (count == 2){
            total.setUnit("GB");
        }else if (count == 3){
            total.setUnit("TB");
        }else {
            total.setUnit("PB");
        }
        return AjaxResult.success(total);
    }


    protected String get32UUID(){
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }


    /**
     * 导出文件记录列表
     */
    @PreAuthorize("@ss.hasPermi('file:flie:export')")
    @Log(title = "文件记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BaseFlieRecord baseFlieRecord)
    {
        List<BaseFlieRecord> list = baseFlieRecordService.selectBaseFlieRecordList(baseFlieRecord);
        ExcelUtil<BaseFlieRecord> util = new ExcelUtil<BaseFlieRecord>(BaseFlieRecord.class);
        return util.exportExcel(list, "文件记录数据");
    }

    /**
     * 获取文件记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('file:flie:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(baseFlieRecordService.selectBaseFlieRecordById(id));
    }

    /**
     * 获取标记文本记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('file:flie:query')")
    @GetMapping(value = "/table/{id}")
    public AjaxResult getInfoByFcode(@PathVariable("id") Long id)
    {
        BaseMaterial baseMaterial = baseMaterialService.selectBMByFileCode(id.intValue());
        if (baseMaterial != null){
            if (baseMaterial.getTabCode() != null)
            return AjaxResult.success(baseFlieRecordService.selectBaseFlieRecordById(baseMaterial.getTabCode()));
        }
        return AjaxResult.error("该素材不存在标记文本信息");
    }

    /**
     * 文件夹记录
     */
    @PreAuthorize("@ss.hasPermi('file:flie:add')")
    @Log(title = "文件夹记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FileRecordVo fileRecord) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        BaseFlieRecord baseFlieRecord = new BaseFlieRecord();
        BaseMaterial baseMaterial = new BaseMaterial();
        baseFlieRecord.setOriginalFileName(fileRecord.getOriginalFileName());
        baseFlieRecord.setCreateBy(loginUser.getUsername());
        baseFlieRecord.setContentType(fileRecord.getContentType());
        baseFlieRecord.setCreateTime(DateUtils.getNowDate());
        baseFlieRecord.setFileSize(0L);
        baseMaterial.setId(RandomlyGeneratedUtil.GeneratID());
        baseMaterial.setCode(RandomlyGeneratedUtil.GeneratID());
        baseMaterial.setpCode(fileRecord.getPCode());
        baseMaterial.setName(fileRecord.getOriginalFileName());
        baseMaterial.setType("folder");
        baseMaterial.setCreateTime(DateUtils.getNowDate());
        baseFlieRecordService.insertBaseFlieRecord(baseFlieRecord);
        List<BaseFlieRecord> list = baseFlieRecordService.selectBaseFlieRecordList(baseFlieRecord);
        System.out.println("id " + list.get(list.size()-1).getId());
        baseMaterial.setFileCode(list.get(list.size()-1).getId());
        baseMaterialService.insertBaseMaterial(baseMaterial);

        return AjaxResult.success("success");
    }

    /**
     * 修改文件记录
     */
    @PreAuthorize("@ss.hasPermi('file:flie:edit')")
    @Log(title = "文件记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseFlieRecord baseFlieRecord,@RequestParam String p_code,@RequestParam String labels)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String updateBy=loginUser != null ? loginUser.getUsername() : "anonymous";
        baseFileLabelService.deleteBaseFileLabelByFileCode(baseFlieRecord.getId().intValue());
        if(labels!="") {
            String[] labelids = labels.split(",");
            Map<Integer,Integer> labelMap=new HashMap<>();//<labelCode,typeCode>
            for(int i=0;i<labelids.length;){
                labelMap.put(Integer.parseInt(labelids[i+1]),Integer.parseInt(labelids[i]));
                i+=2;
            }
            for (Integer labelCode : labelMap.keySet()) {
                System.out.println("labelCode==" + labelCode + "  typeCode" + labelMap.get(labelCode));
                //修改file_label表
                BaseFileLabel baseFileLabel = new BaseFileLabel();
                baseFileLabel.setFileCode(baseFlieRecord.getId());
                baseFileLabel.setLabelCode(labelCode.longValue());
                baseFileLabelService.insertBaseFileLabel(baseFileLabel);
            }
        }
        //修改目录信息
        baseFlieRecord.setUpdateBy(updateBy);
        baseFlieRecord.setUpdateTime(DateUtils.getNowDate());

        BaseMaterial baseMaterial=new BaseMaterial();
        baseMaterial.setFileCode(baseFlieRecord.getId());
        baseMaterial.setName(baseFlieRecord.getOriginalFileName());
        baseMaterial.setUpdateBy(updateBy);
        baseMaterial.setUpdateTime(DateUtils.getNowDate());
        baseMaterial.setpCode(p_code);

        baseMaterialService.updateBaseMaterialByFile_code(baseMaterial);//修改本记录
        logger.debug(baseFlieRecord.toString());
        //修改本记录相对应的标记文件所在路径
        BaseMaterial bm1=baseMaterialService.selectBMByFileCode(baseFlieRecord.getId().intValue());
        if(bm1.getTabCode()!=null) {
            Long newFilecode=bm1.getTabCode();
            BaseMaterial bm2=new BaseMaterial();
            bm2.setName(baseFlieRecord.getOriginalFileName());
            bm2.setFileCode(newFilecode);
            bm2.setUpdateBy(loginUser.getUsername());
            bm2.setUpdateTime(DateUtils.getNowDate());
            bm2.setpCode(p_code);
            baseMaterialService.updateBaseMaterialByFile_code(bm2);
        }
        return toAjax(baseFlieRecordService.updateBaseFlieRecord(baseFlieRecord));
    }

    /**
     * 获取需要删除的文件夹里面的所有东西的id，filecode集合
     * @return
     */
    static int i=0;
    Map<String, Integer> map1 = new HashMap<>();//String为material表的id,,,Integer为material表的filecode即record表的id
    public Map<String,Integer> beforedelFolder(Integer filecode) {
        i=i+1;
        logger.info("*****第"+i+"次递归*****" );
        //根据filecode查找material表的记录
        BaseMaterial BM = baseMaterialService.selectBMByFileCode(filecode);
        if(BM!=null&&BM.getType().equals("folder")){//说明是文件夹
            map1.put(BM.getId(), BM.getFileCode().intValue());//记录下本文件夹的id，准备用于material表的删除...记录下本文件夹的filecode,准备用于Record表的删除
            String p_code=BM.getCode();//记录下code,即获得了p_code
            //获取p_code符合的文件、文件夹
            List<BaseMaterial> BMlist = baseMaterialService.selectBMFilecodesByPcode(p_code);
            if (BMlist.size() > 0) {//大于0说明此文件夹下还有文件或者文件夹
                for (BaseMaterial b : BMlist) {
                    map1.put(b.getId(), b.getFileCode().intValue());//记录下所有文件或文件夹的id，准备用于material表的删除...记录下所有文件或文件夹的filecode,准备用于Record表的删除
                }
                //获取p_code符合的文件夹,用于判断还有没有下一层文件夹
                List<BaseMaterial> folderList = baseMaterialService.selectBMFoldersByPcode(p_code);
                if (folderList.size() > 0) {//获取到，则继续递归下一级文件夹
                    for (BaseMaterial b : folderList) {
                        beforedelFolder(b.getFileCode().intValue());//递归
                    }
                } else {//获取不到，表示没有下一级文件夹了，可以停止
                    logger.info("*****此文件夹下面没有文件夹了*****");
                    return map1;
                }
            }
            else {//小于0说明此文件夹本身为空，无需删除里面的东西
                logger.info("*****此文件夹下面没有任何东西了*****");
                return map1;
            }
        }
        else {//说明是文件
            map1.put(BM.getId(), BM.getFileCode().intValue());
            logger.info("*****说明是文件，记录就行，不用递归*****");
            return map1;
        }
        return map1;
    }
    /**
     * 删除文件记录
     */
    @PreAuthorize("@ss.hasPermi('file:flie:remove')")
    @Log(title = "文件记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Integer[] ids)
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        map1.clear();
        Map<String, Integer> totalMap = new HashMap<>();//String为material表的id,,,Integer为material表的filecode即record表的id
        for (Integer filecode:ids) {
            totalMap.putAll(beforedelFolder(filecode));
        }
        int result1=0,result2=0;

        //批量删除
        List<String> idList=new ArrayList<>();
        List<Integer> filecodes = new ArrayList<>();
        List<Integer> tabcodes = new ArrayList<>();
        for (String id:totalMap.keySet()) {
            logger.info("要删除的东西有id为======="+id+"   filecode为======"+totalMap.get(id));
            //if()根据id查到不是文件夹folder或者标记文件txt，则记录tabcode,,,,,else记录不用tabcode
            BaseMaterial baseMaterial=baseMaterialService.selectBaseMaterialById(id);
            Boolean flag1=baseMaterial.getType().equals("folder");//是否是文件夹
            Boolean flag2=baseMaterial.getType().equals("text/plain");//是否是标记文本
            System.out.println(baseMaterial);
//            Boolean flag3=baseMaterial.getTabCode().equals("-1")||baseMaterial.getTabCode().equals("")||baseMaterial.getTabCode().equals(null)||baseMaterial.getTabCode().equals("");//tabCode是否是空或者-1
            System.out.println("flag1="+flag1+"   flag2="+flag2);
            if(!flag1&&!flag2) {
                tabcodes.add(baseMaterial.getTabCode().intValue());
                System.out.println("记下tabcode="+baseMaterial.getTabCode());
            }
            idList.add(id);
            filecodes .add(totalMap.get(id)) ;
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String updateBy=loginUser != null ? loginUser.getUsername() : "anonymous";
        //删除图片文件
        result1 = baseMaterialService.delBaseMaterialList(idList,updateBy);
        result2=baseFlieRecordService.delBaseFlieRecordList(filecodes,updateBy);
//        删除标记文件
        baseMaterialService.delBaseMaterialListByFileCode(tabcodes,updateBy);
        baseFlieRecordService.delBaseFlieRecordList(tabcodes,updateBy);
//        删除标记记录
        baseTagFileService.delTagFileByFileCode(tabcodes,updateBy);
//        删除标签
        baseFileLabelService.delBaseFlieLabelListByFileCodes(filecodes);
//        根据id(code)找到tabcode      material表
//        根据tabcode找到filecode为这个tabcode的记录，即标记文件记录， material表
//        根据上个filecode找到record表的这个记录，删除它，
//        根据上个filecode找到tag表的这些个记录，删除他们
        if(result1>0&&result2>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }


    Integer jpgID=-1;
    Integer txtID=-1;
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile[] multipartFileArray ,@RequestParam Map<String,String> codeMap) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String labs=null;
        for(String X:codeMap.keySet()){
            System.out.println("showcodmap:key:"+X+"  value:"+codeMap.get(X));
        }
        Map<Long,String> map = null;//key为id,value为original_file_name
        map=uploadInBaseFileRecord(multipartFileArray);
        if(multipartFileArray.length<2){//保证只上传原图，没有标记文件的时候，图片文件的tabcode为-1，而不是上一个残留值，即tabcode=-1时为原图，无标记文件
            txtID=-1;
        }
        List<BaseMaterial> baseMaterialList = Lists.newArrayList();
        for (Long id:map.keySet()) {
            String name=map.get(id);
            if (multipartFileArray.length > 0) {
                for (int i = 0; i < multipartFileArray.length; i++) {
                    if (i == 2) {
                        break;
                    }
                    MultipartFile multipartFile = multipartFileArray[i];
                    logger.info("===BaseFlieRecordController===uploadFile()===[文件大小：]===" + multipartFile.getSize());
                    logger.info("===BaseFlieRecordController===uploadFile()===[文件名称：]===" + multipartFile.getOriginalFilename());
                    logger.info("===BaseFlieRecordController===uploadFile()===[文件类型：]===" + multipartFile.getContentType());
                    String baseMaterialID = RandomlyGeneratedUtil.GeneratID();
                    if(multipartFile.getContentType().equals("video/mp4")||multipartFile.getContentType().equals("text/plain")||multipartFile.getContentType().equals("image/jpeg")) {
                        if (multipartFile.getOriginalFilename().equals(name)) {//文件名对应上，即可找到对应的file_code，
                            for (String key : codeMap.keySet()) {
                                if (key.equals("pcode")) {
                                    Long fileCode = id;
                                    BaseMaterial baseMaterial2 = new BaseMaterial();
                                    baseMaterial2.setId(baseMaterialID);
                                    baseMaterial2.setCode(baseMaterialID);
                                    baseMaterial2.setpCode(codeMap.get(key));
                                    baseMaterial2.setName(multipartFile.getOriginalFilename());
                                    baseMaterial2.setType(multipartFile.getContentType());
                                    baseMaterial2.setFileCode(Long.valueOf(fileCode));
                                    baseMaterial2.setCode(baseMaterialID);
                                    baseMaterial2.setCreateBy(loginUser != null ? loginUser.getUsername() : "anonymous");
                                    baseMaterialList.add(baseMaterial2);
                                } else {
                                    labs = codeMap.get(key);
                                }
                            }
                        }
                    }
                }
            }
        }

        if (baseMaterialList.size()>0)
        {
            baseMaterialService.addBaseMaterialList(baseMaterialList);
            //以下是tabcode获取和插入
            for (Long id:map.keySet()) {
                String str1 = map.get(id).substring(0, map.get(id).indexOf("."));
                String str2 = map.get(id).substring(str1.length()+1);
                if(!str2.equals("txt")){
                    jpgID=id.intValue();
                    if(!labs.trim().equals("")) {
                        String[] labels = labs.split(",");
                        Map<Integer, Integer> labelMap = new HashMap<>();
                        for (int i = 0; i < labels.length; ) {
                            labelMap.put(Integer.parseInt(labels[i + 1]), Integer.parseInt(labels[i]));
                            i += 2;
                        }
                        for (Integer labelCode : labelMap.keySet()) {
                            System.out.println("x==" + labelCode + "  value" + labelMap.get(labelCode));
                            BaseFileLabel baseFileLabel = new BaseFileLabel();
                            baseFileLabel.setFileCode(jpgID.longValue());
                            baseFileLabel.setLabelCode(labelCode.longValue());
                            baseFileLabelService.insertBaseFileLabel(baseFileLabel);
                        }
                    }
                    //根据labelmap.valueSet获得List，批量找到这些id的标签名称
                }
                if(str2.equals("txt")){
                    txtID=id.intValue();
                }
            }
            baseMaterialService.updateBaseMaterialByFileCode(jpgID, txtID);

            return AjaxResult.success("上传成功", baseMaterialList);
        }
        return AjaxResult.error();
    }

    /**
     * 检查文件的标签是否存在，并新增
     */
    private List<BaseLabel> checkLabelNames(String[] labels, String createBy) {
        List<BaseLabel> res = new ArrayList<>();
        for (String label : labels) {

            BaseLabel select = baseLabelService.selectBaseLabelByLabel(label);
            if (select == null) {
                select = new BaseLabel();
                select.setLabel(label);
                select.setCreateTime(DateUtils.getNowDate());
                select.setCreateBy(createBy);
                baseLabelService.insertBaseLabel(select);
            }
            res.add(select);
        }
        return res;
    }

//    先存入BaseFileRecord,获取它的id作为BaseMaterial的file_code，用于上传
    public Map<Long,String> uploadInBaseFileRecord(@RequestParam("file") MultipartFile[] multipartFileArray ) throws Exception {
        Map<Long,String> map = new HashMap<>();;//key为id,value为original_file_name
        if (multipartFileArray.length > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            List<BaseFlieRecord> baseFlieRecordList = Lists.newArrayList();
            for (int i = 0; i < multipartFileArray.length; i++) {
                if (i == 2) {
                    break;
                }

                MultipartFile multipartFile = multipartFileArray[i];
                String uploadPath = RuoYiConfig.getUploadPath();
                logger.info("===BaseFlieRecordController===uploadFile()===[文件大小：]===" + multipartFile.getSize());
                logger.info("===BaseFlieRecordController===uploadFile()===[文件名称：]===" + multipartFile.getOriginalFilename());
                logger.info("===BaseFlieRecordController===uploadFile()===[文件类型：]===" + multipartFile.getContentType());
                String pathFileName = FileUploadUtils.upload(uploadPath, multipartFile);
                logger.info("===BaseFlieRecordController===uploadFile()===[上传后的路径：]===" + pathFileName);

                BaseFlieRecord baseFlieRecord = new BaseFlieRecord()
                        .setOriginalFileName(multipartFile.getOriginalFilename())
                        .setFileSize(multipartFile.getSize())
                        .setContentType(multipartFile.getContentType())
                        .setPathFileName(pathFileName);
                baseFlieRecord.setCreateBy(loginUser != null ? loginUser.getUsername() : "anonymous");
                baseFlieRecordList.add(baseFlieRecord);
            }

            if (baseFlieRecordList.size() > 0) {
                baseFlieRecordService.addBaseFlieRecordList(baseFlieRecordList);
                for (BaseFlieRecord b:baseFlieRecordList ) {
                    String pathFileName1= b.getPathFileName();
                    BaseFlieRecord baseFlieRecord=baseFlieRecordService.selectBaseFlieRecordByPathFileName(pathFileName1);//根据pathFileName找到各个插入的记录的id
                    Long id=baseFlieRecord.getId();
                    String name=baseFlieRecord.getOriginalFileName();
                    map.put(id,name);
                    if(baseFlieRecord.getContentType().equals("text/plain")){
                        Map<String,String> inforMap=new HashMap<>();
                        inforMap=readTxt(baseFlieRecord);
                        System.out.println(inforMap.size());
                        if(inforMap.size()>0) {
                            List<BaseTagFile> baseTagFileList = new ArrayList<>();
                            for (String temp : inforMap.keySet()) {
                                BaseTagFile baseTagFile = new BaseTagFile();
                                baseTagFile.setFileCode(id);
                                baseTagFile.setTagCategory(Long.parseLong(temp.split(" ")[0]));
                                baseTagFile.setTagInfo(inforMap.get(temp));
                                baseTagFile.setCreateBy(loginUser != null ? loginUser.getUsername() : "anonymous");
                                baseTagFile.setCreateTime(DateUtils.getNowDate());
                                baseTagFileList.add(baseTagFile);
                            }
                            baseTagFileService.addBaseTagFileList(baseTagFileList);
                        }
                    }
                }
                return map;
            }
        }
        return map;
    }

    //读取txt标记文件内容，按行读取
    public Map<String,String> readTxt(BaseFlieRecord baseFlieRecord) throws Exception {
        String pathFileName=baseFlieRecord.getPathFileName().substring(15);
        Map<String,String> inforMap=new HashMap<>();
        File file=new File(RuoYiConfig.getUploadPath()+pathFileName);
        BufferedReader reader=null;
        String temp=null;
        int line=1;
        try{
            reader=new BufferedReader(new FileReader(file));
            while((temp=reader.readLine())!=null){
                System.out.println("line"+line+":"+temp);
                String[] info = temp.split(" ");
                String str="";
                for(int i=1;i<info.length;i++){
                    str+=info[i]+" ";
                }
                inforMap.put(temp,str);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            if(reader!=null){
                try{
                    reader.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        return inforMap;
    }



    @RequiresPermissions("")
    @PostMapping("/downloadFile/{fileId}")
    public void downloadFile(@PathVariable("fileId")Integer fileId, HttpServletResponse response,
                                                            HttpServletRequest request)throws Exception{
        BaseFlieRecord baseFlieRecord = baseFlieRecordService.selectBaseFlieRecordById(fileId.longValue());
        boolean delete = false;
        String fileName =  baseFlieRecord.getPathFileName();
        try
        {
            String downloadPath = "";
            String realFileName = "";
            if (baseFlieRecord.getContentType().equals(FileConstant.FOLDER_TYPE)){
                downloadPath = baseMaterialService.downloadMaterialByCode(baseFlieRecord.getId());
                myDownLoad(downloadPath,baseFlieRecord.getOriginalFileName(),response,request);
                return;
            }else {
                realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
                // 本地资源路径
                String localPath = RuoYiConfig.getProfile();
                // 数据库资源地址
                downloadPath = localPath + StringUtils.substringAfter(baseFlieRecord.getPathFileName(), Constants.RESOURCE_PREFIX);
                logger.info("BaseFlieRecordController.downloadFile() 文件真实名称 [{}] 数据库资源地址 [{}] 访问地址 [{}]",realFileName,downloadPath,baseFlieRecord.getPathFileName());
            }

            logger.debug("真实图片的名字 【{}】",realFileName);
            logger.debug("图片的位置 【{}】",downloadPath);
            logger.debug("访问地址 【{}】",baseFlieRecord.getPathFileName());
            String filePath = downloadPath;
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            FileUtils.setAttachmentResponseHeader(response, realFileName);
            logger.debug("图片的位置 【 filePath {}】",filePath);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }


        }
        catch (Exception e)
        {
            logger.error("下载文件失败", e);
        }
    }

    /**
     * 把压缩文件响应给前端
     * @param filePath 压缩文件路径 ##/###/**.zip
     * @param fileName 文件名称  **.zip
     * @param response
     * @param request
     */
    public void myDownLoad(String filePath,String fileName, HttpServletResponse response, HttpServletRequest request){
        String filePathF = filePath ;
        File f = new File(filePathF);
        if (!f.exists()) {
            try {
                response.sendError(404, "File not found!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(filePathF));
            byte[] buffer = new byte[fis.available()];
            int index = fis.read(buffer); // 不能删除，否则压缩包解压不开（能正常下载）
            fis.close();
            //清空response
            response.reset();
            //设置response的Header
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-disposition", "attachment; filename=" + fileName);
            response.addHeader("Content-Length",""+f.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private int isFile(String type){
        if (type.startsWith("f")){
            return 0;
        }else if (type.startsWith("i")){
            return  1;
        }else if (type.startsWith("v")){
            return  2;
        }else {
            return  3;
        }
    }

    /**
     * 下拉树结构
     * @param dept
     * @return
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        return AjaxResult.success(baseMaterialService.buildMaterialTreeSelect());
    }

}
